package net.wanho.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.constant.UserConstant;
import net.wanho.dto.LoginDTO;
import net.wanho.exception.CaptchaException;
import net.wanho.exception.LoginErrorException;
import net.wanho.mapper.UserMapper;
import net.wanho.po.User;
import net.wanho.service.CaptchaService;
import net.wanho.service.LoginService;
import net.wanho.util.JwtUtils;
import net.wanho.util.PwdUtils;
import net.wanho.vo.LoginUserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-08-24 16:42
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserMapper userMapper;
    private final CaptchaService captchaService;

    @Override
    public LoginUserVo login(LoginDTO loginDTO) {
        /**
         * 判断验证码
         */
        try {
            captchaService.check(loginDTO.getUuid(),loginDTO.getCode());
        } catch (Exception e) {
            throw new CaptchaException(e.getMessage());
        }

        /**
         * 判断用户
         */
        User user = userMapper.selectByUsername(loginDTO.getUsername());
        if (ObjectUtils.isEmpty(user)){
            throw new LoginErrorException("用户不存在");
        }
        if (!user.getPassword().equals(PwdUtils.encrypt(loginDTO.getPassword()))){
            throw new LoginErrorException("密码错误");
        }
        if (user.getStatus() == UserConstant.DISABLE){
            throw new LoginErrorException("用户已被禁用");
        }

        /**
         * 生成token
         */
        Map<String,Object> payload = new HashMap<>();
        payload.put("id",user.getId());
        payload.put("username",user.getUsername());
        String token = JwtUtils.generate(payload);

        /**
         * 返回用户信息
         */
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(user.getId());
        loginUserVo.setUsername(user.getUsername());
        loginUserVo.setToken("Bearer " + token); // 在返回令牌时习惯上添加前缀"Bearer "
        return loginUserVo;
    }
}
